package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.BrandDTO;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class BrandService extends ServiceImpl<BrandMapper, Brand> implements com.leyou.item.service.BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<Brand> queryBrandsByids(List<Long> ids) {
        List<Brand> brands = listByIds(ids);
        return brands;
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {


        // 分页条件定义
        IPage<Brand> iPage=new Page<>(page,rows);
        // 判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        // 如果key存在，添加like和eq的查询条件，否则不添加
        page(iPage,new QueryWrapper<Brand>()
                .like(isKeyExists,"name",key)
                .or()
                .eq(isKeyExists,"letter",key));
        //封装分页结果返回
        return new PageDTO<>(iPage.getTotal(),iPage.getPages(),BrandDTO.convertEntityList(iPage.getRecords()));
    }



    @Override
    public List<BrandDTO> listBrandById(Long id) {
        List<Brand> brands = getBaseMapper().listBrandById(id);

        return BrandDTO.convertEntityList(brands);
    }




    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream().map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);
    }
}
